package com.bdd.aspect;

import com.bdd.Result.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * @description 返回值处理切面
 * @author huanghaining
 * @date 2022/3/18
 */

@Aspect
@Component
public class ControllerAspect {

    //拦截@RestController修饰的controller
    //以及 @RestController修饰的切面 一般是全局异常处理
    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) " +
            "|| @within(org.springframework.web.bind.annotation.RestControllerAdvice)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object afterRun(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret = joinPoint.proceed();

        if (!(ret instanceof Result)) {
            return ret;
        }
        Result res = (Result) ret;
        //获取当前service的request reponse对象
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();

        if (attr == null) {
            throw new IllegalStateException("Not a http requeat");
        }

        HttpServletResponse response = attr.getResponse();
        if (response == null) {
            throw new IllegalStateException("Not a http reponse");
        }
        response.setStatus(res.getCode().getHttpStatus().value());
        return res;
    }

}
